package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.item.entity.*;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.service.*;
import com.netflix.eureka.Names;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper, Spu> implements SpuService {

    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageDTO<SpuDTO> goodsPageQuery(Integer page, Integer rows) {

        IPage<Spu> iPage = new Page<>(page,rows);
        page(iPage);
        List<SpuDTO> spuDTOS = SpuDTO.convertEntityList(iPage.getRecords());

        for (SpuDTO spuDTO : spuDTOS) {
            //根据分类id的集合查询对应的分类集合，并取出分类名称并拼接为字符串
            String names = this.categoryService.queryCategoryById(spuDTO.getCategoryIds())
                    .stream()
                    .map(CategoryDTO::getName)
                    .collect(Collectors.joining("/"));
            spuDTO.setCategoryName(names);
            //根据brandId查询对应品牌的名字
            spuDTO.setBrandName(this.brandService.getById(spuDTO.getBrandId()).getName());
        }
        return new PageDTO<>(iPage.getTotal(),iPage.getPages(),spuDTOS);
    }
}
